<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class De_form_model extends MY_Model {

    function __construct() {
        parent::__construct("form", "id", Array(
                ), "data_ps");
        $this->delAttribute = "is_deleted";
    }

    public function create($dataArr) {
        $formId = 0;
        if (count($dataArr) > 0) {
            $this->load->library('session');
            $this->db->insert("form", Array(
                "user_email" => $this->session->userdata('useremail'),
                "input_time" => date("Y-m-d H:i:s"),
                "is_approved" => false,
                "is_deleted" => false
            ));
            $formId = $this->db->insert_id();
            if ($formId > 0) {
                $this->updateData($formId, $dataArr);
            }
        }
        return $formId;
    }

    public function updateData($id, $dataArr) {
        $formObj = $this->findById($id);
        if ($formObj != NULL) {
            foreach ($dataArr as $data) {
                $this->load->database("data_ps");
                $this->db->select("id");
                $this->db->from("data");
                $this->db->where("form_id", $id);
                $this->db->where("year", $data->year);
                $this->db->where("month", $data->month);
                $this->db->where("source_id", $data->source_id);
                $this->db->where("indicator_id", $data->indicator_id);
                switch ($data->level) {
                    case "REG" :
                        $this->db->from("region_data");
                        $this->db->where("region_code", $data->loc_code);
                        $this->db->where("data_id = id");
                        break;
                    case "PROV" :
                        $this->db->from("provinsi_data");
                        $this->db->where("provinsi_code", $data->loc_code);
                        $this->db->where("data_id = id");
                        break;
                    case "KAB" :
                        $this->db->from("kabupaten_data");
                        $this->db->where("kabupaten_code", $data->loc_code);
                        $this->db->where("data_id = id");
                        break;
                    case "KEC" :
                        $this->db->from("kecamatan_data");
                        $this->db->where("kecamatan_code", $data->loc_code);
                        $this->db->where("data_id = id");
                        break;
                    case "DESA" :
                        $this->db->from("perdesaan_data");
                        $this->db->where("perdesaan_code", $data->loc_code);
                        $this->db->where("data_id = id");
                        break;
                    case "PUSKESMAS" :
                        $this->db->from("puskesmas_data");
                        $this->db->where("puskesmas_id", $data->loc_code);
                        $this->db->where("data_id = id");
                        break;
                    default :
                        $this->db->where("0");
                        break;
                }
                $query = $this->db->get();
                $result = $query->result();
                if (count($result) > 0) {
                    $ids = "";
                    foreach ($result as $row) {
                        if ($ids != "") {
                            $ids .= ",";
                        }
                        $ids .= $row->id;
                    }
                    $this->db->update("data", Array("value" => trim($data->value), "is_deleted" => 0), "id IN (" . $ids . ")");
                    echo "<br /><br />updated : ";
                    print_r($data);
                } else {
                    $this->load->model("De_data_model");
                    $dataId = $this->De_data_model->create($id, $data->year, $data->month, $data->source_id, $data->level, $data->loc_code, $data->indicator_id, trim($data->value));
                    if ($dataId > 0) {
                        echo "<br /><br />created : ";
                        print_r($data);
                    } else {
                        echo "<br /><br />failed : ";
                        print_r($data);
                    }
                }
            }
            $this->updateById($id, Array("input_time" => date("Y-m-d H:i:s")));
        }
    }

    public function parseUpdate($id, $metaText, $dataText) {
        $dataArr = Array();

        // parse meta
        $metaArr = Array();
        foreach (explode(";", $metaText) as $col) {
            $meta = strtoupper(trim($col));
            switch ($meta) {
                case "KODE_REG" :
                case "KODE_PROV" :
                case "NAMA_PROV" :
                case "KODE_KAB" :
                case "NAMA_KAB" :
                case "KODE_KEC" :
                case "NAMA_KEC" :
                case "KODE_DESA" :
                case "NAMA_DESA" :
                case "TAHUN" :
                case "BULAN" :
                case "SUMBER_DATA" :
                    break;
                default : // filter indicator
                    $this->load->model("De_indicator_model");
                    $ind = $this->De_indicator_model->findById($meta);
                    if ($ind == NULL) {
                        $meta = ""; // skipping col
                    }
                    break;
            }
            array_push($metaArr, $meta);
        }

        print_r($metaArr);
        echo "<hr />";

        // parse data
        foreach (explode("\n", $dataText) as $row) {
            $idx = 0;
            $vals = Array();
            $year = NULL;
            $month = NULL;
            $sourceId = NULL;
            $dataLevel = NULL;
            $locId = NULL;
            foreach (explode(";", $row) as $col) {
                if ($idx > (count($metaArr) - 1)) {
                    break;
                }
                $val = trim($col);
                $colType = $metaArr[$idx];
                switch ($colType) {
                    case "KODE_REG" :
                        $dataLevel = "REG";
                        $locId = $val;
                        break;
                    case "KODE_PROV" :
                        $dataLevel = "PROV";
                        $locId = $val;
                        break;
                    case "NAMA_PROV" :
                        $dataLevel = "PROV";
                        $this->load->model("Provinsi_model");
                        $provObj = $this->Provinsi_model->findByName($val);
                        if ($provObj != NULL) {
                            $locId = $provObj->code;
                        } else {
                            echo "<br />Can't find Provinsi " . $val;
                        }
                        break;
                    case "KODE_KAB" :
                        $dataLevel = "KAB";
                        $locId = $val;
                        break;
                    case "NAMA_KAB" :
                        $dataLevel = "KAB";
                        $this->load->model("Kabupaten_model");
                        $kabObj = $this->Kabupaten_model->findByName($val);
                        if ($kabObj != NULL) {
                            $locId = $kabObj->code;
                        } else {
                            echo "<br />Can't find Kabupaten " . $val;
                        }
                        break;
                    case "KODE_KEC" :
                        $dataLevel = "KEC";
                        $locId = $val;
                        break;
                    case "NAMA_KEC" :
                        $dataLevel = "KEC";
                        $this->load->model("Kecamatan_model");
                        $kecObj = $this->Kecamatan_model->findByName($val);
                        if ($kecObj != NULL) {
                            $locId = $kecObj->code;
                        } else {
                            echo "<br />Can't find Kecamatan " . $val;
                        }
                        break;
                    case "KODE_DESA" :
                        $dataLevel = "DESA";
                        $locId = $val;
                        break;
                    case "NAMA_DESA" :
                        $dataLevel = "DESA";
                        $this->load->model("Perdesaan_model");
                        $desaObj = $this->Perdesaan_model->findByName($val);
                        if ($desaObj != NULL) {
                            $locId = $desaObj->code;
                        } else {
                            echo "<br />Can't find Perdesaan " . $val;
                        }
                        break;
                    case "TAHUN" :
                        $year = $val;
                        break;
                    case "BULAN" :
                        $month = $val;
                        break;
                    case "SUMBER_DATA" :
                        $this->load->model("De_source_model");
                        $sources = $this->De_source_model->findAll(
                                "code LIKE '" . $val . "' OR name LIKE '" . $val . "'"
                        );
                        if (count($sources) > 0) {
                            $sourceId = $sources[0]->id;
                        } else {
                            $sourceId = $this->De_source_model->create($val, $val, $val);
                        }
                        break;
                    default : // indicator
                        array_push($vals, Array(
                            "indicator_id" => $colType,
                            "value" => $val
                        ));
                        break;
                }
                $idx++;
            }
            foreach ($vals as $rowVal) {
                if ((intval($rowVal["indicator_id"]) > 0) && (strlen($rowVal["value"]) > 0)) {
                    $dataObj = new stdClass();
                    $dataObj->year = $year;
                    $dataObj->month = $month;
                    $dataObj->source_id = $sourceId;
                    $dataObj->level = $dataLevel;
                    $dataObj->loc_code = $locId;
                    $dataObj->indicator_id = $rowVal["indicator_id"];
                    $dataObj->value = $rowVal["value"];
                    array_push($dataArr, $dataObj);
                } else {
                    echo "<br /> Skipped : " . print_r($rowVal);
                }
            }
        }

        if ($this->findById($id) == NULL) {
            $this->create($dataArr);
        } else {
            $this->updateData($id, $dataArr);
        }
    }

}